package cn.iocoder.an.module.mold.service.storage;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.module.mold.controller.admin.account.vo.AccountImportExcelVO;
import cn.iocoder.an.module.mold.dal.dataobject.category.CategoryDO;
import cn.iocoder.an.module.mold.dal.dataobject.warehouse.WarehouseDO;
import cn.iocoder.an.module.mold.service.warehouse.WarehouseService;
import cn.iocoder.an.module.mold.utils.ImportRespVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import cn.iocoder.an.module.mold.controller.admin.storage.vo.*;
import cn.iocoder.an.module.mold.dal.dataobject.storage.StorageDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.mold.dal.mysql.storage.StorageMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.module.mold.enums.ErrorCodeConstants.*;

/**
 * 模具储位 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class StorageServiceImpl implements StorageService {

    @Resource
    private StorageMapper storageMapper;

    @Resource
    private WarehouseService warehouseService;

    @Override
    public Long createStorage(StorageSaveReqVO createReqVO) {
        // 插入
        StorageDO storage = BeanUtils.toBean(createReqVO, StorageDO.class);
        storageMapper.insert(storage);

        // 返回
        return storage.getId();
    }

    @Override
    public void updateStorage(StorageSaveReqVO updateReqVO) {
        // 校验存在
        validateStorageExists(updateReqVO.getId());
        // 更新
        StorageDO updateObj = BeanUtils.toBean(updateReqVO, StorageDO.class);
        storageMapper.updateById(updateObj);
    }

    @Override
    public void deleteStorage(Long id) {
        // 校验存在
        validateStorageExists(id);
        // 删除
        storageMapper.deleteById(id);
    }

    @Override
    public void deleteStorageListByIds(List<Long> ids) {
        // 删除
        storageMapper.deleteByIds(ids);
    }


    private void validateStorageExists(Long id) {
        if (storageMapper.selectById(id) == null) {
            throw exception(STORAGE_NOT_EXISTS);
        }
    }

    @Override
    public StorageDO getStorage(Long id) {
        return storageMapper.selectById(id);
    }


    @Override
    public List<StorageDO> listOfWarehouse(Long warehouseId) {
        return storageMapper.selectList(new LambdaQueryWrapper<>(StorageDO.class)
                .eq(StorageDO::getWarehouseId, warehouseId));
    }

    @Override
    public List<StorageDO> getStorageAll() {
        return storageMapper.selectList();
    }

    @Override
    public PageResult<StorageDO> getStoragePage(StoragePageReqVO pageReqVO) {
        return storageMapper.selectPage(pageReqVO);
    }

    @Override
    public Long getStorageId(Long warehouseId, String storageCode) {
        StorageDO storage = storageMapper.selectFirstOne(StorageDO::getWarehouseId, warehouseId, StorageDO::getCode, storageCode);
        if (storage != null) {
            return storage.getId();
        } else {
            throw exception(STORAGE_NOT_EXISTS);
        }
    }


    @Override
    public ImportRespVO importStorageList(List<StorageImportExcelVO> iomportStorage, boolean isUpdateSupport) {
        if (CollUtil.isEmpty(iomportStorage)) {
            throw exception(STORAGE_NOT_EXISTS);
        }
        ImportRespVO respVO = ImportRespVO.builder().insertNameList(new ArrayList<>())
                .updateNameList(new ArrayList<>()).failureMap(new LinkedHashMap<>()).build();
        AtomicInteger count = new AtomicInteger(1);
        iomportStorage.forEach(item -> {
            count.incrementAndGet();//记录行号
            // 2.1.1 校验编码
            if (StringUtils.isEmpty(item.getCode())) {
                return;
            }
            // 2.1.2 校验名称
            if (StringUtils.isEmpty(item.getName())) {
                respVO.getFailureMap().put(item.getCode(), "名称不能为空!");
                return;
            }

            // 2.1.4 仓库编码
            if (StringUtils.isEmpty(item.getWarehouseCode())) {
                respVO.getFailureMap().put(item.getCode(), "仓库编码不能为空!");
                return;
            } else {
                try {
                    item.setWarehouseId(warehouseService.getWarehouseIdByCode(item.getWarehouseCode()));
                } catch (Exception e) {
                    respVO.getFailureMap().put(item.getCode(), e.getMessage());
                    return;
                }
            }

            //更新或者插入
            //判断图号是否重复
            String code = item.getCode();
            StorageDO exists = storageMapper.selectFirstOne(
                    StorageDO::getCode, code
            );
            if (exists != null) {
                if (isUpdateSupport) {
                    //允许更新
                    //设置ID
                    item.setId(exists.getId());
                    StorageDO storageDO = BeanUtils.toBean(item, StorageDO.class);
                    storageMapper.updateById(storageDO);
                    respVO.getUpdateNameList().add(item.getCode());
                } else {
                    respVO.getFailureMap().put(item.getCode(), STORAGE_CODE_EXISTS.getMsg());
                }
            } else {
                storageMapper.insert(BeanUtils.toBean(item, StorageDO.class));
                respVO.getInsertNameList().add(item.getCode());
            }
        });
        return respVO;
    }
}